import json
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from django.core import serializers
import smtplib, logging
from email.mime.text import MIMEText

logger = logging.getLogger('log')
from django.http import JsonResponse
# 只能用相对路径 绝对路径会报错
from ..models import ptTestEmail
from ..serverEvCfg import httpResponseSignal


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def getAllEmail(request):
    """
    获取所有邮件列表返回
    """
    try:
        emailList = ptTestEmail.objects.all()
        data = json.loads(serializers.serialize("json", emailList))
        print(data)
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["data"] = data
        return JsonResponse(response)
    except Exception as e:
        logging.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr()
        return JsonResponse(response)


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def addEmail(request):
    """
    添加修改邮件
    """
    data = json.loads(request.body)
    try:
        emailRecList = []  # 收件人列表
        rec = data["domains"]  # 收件人
        for i in range(len(rec)):
            val = rec[i]["value"]
            emailRecList.append(val)
        if data["id"] == "":  # 新增邮件
            newEmail = ptTestEmail(host=data["host"],
                                   port=data["port"],
                                   user=data["user"],
                                   passWD=data["passWD"],
                                   sender=data["sender"],
                                   receivers=emailRecList)
        else:  # 修改邮件
            oldEmail = ptTestEmail.objects.get(id=data["id"])
            oldEmail.host = data["host"]
            oldEmail.port = data["port"]
            oldEmail.user = data["user"]
            oldEmail.passWD = data["passWD"]
            oldEmail.sender = data["sender"]
            oldEmail.receivers = emailRecList

        response = httpResponseSignal().getSuccess()
        response["data"] = data
        return JsonResponse(response)
    except Exception as e:
        logging.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr()
        return JsonResponse(response)


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def sendEmail(request):
    """
    发送邮件
    """
    data = json.loads(request.body)
    try:
        emailRecList = []  # 收件人列表
        rec = data["domains"]  # 收件人
        for i in range(len(rec)):
            val = rec[i]["value"]
            emailRecList.append(val)

        host = data["host"]  # SMTP服务器
        port = int(data["port"])
        user = data["user"]  # 用户名
        passWD = data["passWD"]  # 授权密码，非登录密码
        sender = data["sender"]  # 发邮件人
        receivers = emailRecList  # 收邮件人
        subject = '测试邮件'  # 邮件主题
        content = "---邮件已成功发送---"
        meg = MIMEText(content + ' \n apiPT', _subtype='html', _charset='utf-8')  # 内容, 格式, 编码
        meg['From'] = user  # 这两种方法都一样的
        meg['From'] = "{}".format(user)
        meg['To'] = ','.join(receivers)
        meg['Subject'] = subject + '(测试链接邮件)'

        smtpObj = smtplib.SMTP_SSL(host, port)  # 启用SSL发信, 端口一般是465
        smtpObj.login(user, passWD)  # 登录验证
        smtpObj.sendmail(sender, receivers, meg.as_string())  # 发送
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["msg"] = "邮件发送成功"
        return JsonResponse(response)

    except smtplib.SMTPException as e:
        logger.error(e)
        response = httpResponseSignal.httpResponseSignal().getFail()
        request["msg"] = "邮件发送失败"
        return JsonResponse(response)
    except Exception as e:
        logger.error(e)
        response = httpResponseSignal.httpResponseSignal().getFail()
        response["msg"] = "邮件发送异常，请仔细检查格式"
        return JsonResponse(response)
